import { NextResponse } from "next/server"
import { getOnlineUsers, createAnonymousUser, updateUserLastSeen } from "@/lib/neon-db"

export async function GET() {
  try {
    console.log("GET /api/users: Fetching online users")
    const users = await getOnlineUsers()
    console.log(`GET /api/users: Found ${users.length} online users`)
    return NextResponse.json({ users })
  } catch (error: any) {
    console.error("Error in GET /api/users:", error)
    // Return a more detailed error response
    return NextResponse.json(
      {
        error: "Failed to fetch online users",
        details: error.message || "Unknown database error",
        users: [], // Return empty array to prevent client-side errors
      },
      { status: 500 },
    )
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { nickname, avatarSeed } = body

    console.log("Received user creation request:", { nickname, avatarSeed })

    if (!nickname || !avatarSeed) {
      console.error("Missing required fields:", { nickname, avatarSeed })
      return NextResponse.json({ error: "Nickname and avatar seed are required" }, { status: 400 })
    }

    const user = await createAnonymousUser(nickname, avatarSeed)
    console.log("User created in database:", user)

    return NextResponse.json({ user })
  } catch (error: any) {
    console.error("Error in POST /api/users:", error)
    return NextResponse.json({ error: error.message || "Failed to create user" }, { status: 500 })
  }
}

export async function PUT(request: Request) {
  try {
    const { userId } = await request.json()

    if (!userId) {
      return NextResponse.json({ error: "User ID is required" }, { status: 400 })
    }

    const success = await updateUserLastSeen(userId)

    return NextResponse.json({ success })
  } catch (error: any) {
    console.error("Error in PUT /api/users:", error)
    return NextResponse.json({ error: "Failed to update user" }, { status: 500 })
  }
}
